package com.link.play.fit.ai.ui.scanFood

import android.app.Activity
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.activity.addCallback
import androidx.core.content.FileProvider
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.google.gson.Gson
import com.link.play.fit.ai.R
import com.link.play.fit.ai.base.BaseActivity
import com.link.play.fit.ai.base.goToAcForResult
import com.link.play.fit.ai.bean.CollectFoodInfoData
import com.link.play.fit.ai.bean.RecentlyEatenData
import com.link.play.fit.ai.bean.ScanIngredientBean
import com.link.play.fit.ai.bean.build
import com.link.play.fit.ai.bean.toCollectFoodInfoData
import com.link.play.fit.ai.databinding.AcFoodDetailBinding
import com.link.play.fit.ai.ext.d
import com.link.play.fit.ai.ext.setThrottleListener
import com.link.play.fit.ai.store.CloudStore
import com.link.play.fit.ai.store.CloudStore.DOC_SAVE_FOOD_COLLECT_DATA
import com.link.play.fit.ai.store.CloudStore.deleteList
import com.link.play.fit.ai.ui.guide.EditPlanGoalAc
import com.link.play.fit.ai.ui.guide.TYPE_CALORIES
import com.link.play.fit.ai.ui.guide.TYPE_CARBS
import com.link.play.fit.ai.ui.guide.TYPE_FATS
import com.link.play.fit.ai.ui.guide.TYPE_PROTEIN
import com.link.play.fit.ai.ui.main.GlobalViewModel
import com.link.play.fit.ai.ui.main.saveFood.details.FixResultAc
import com.link.play.fit.ai.utils.DateEx
import com.link.play.fit.ai.utils.ShareFileUtils.getFileUri
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import java.io.File
import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter


class FoodDetailAc : BaseActivity<AcFoodDetailBinding>(AcFoodDetailBinding::inflate) {
    private var dataR: RecentlyEatenData = RecentlyEatenData()
    private val adapter = IngredientsAdapter()
    private var mIngredientsList: List<ScanIngredientBean> = listOf()
    private var mulValue = MutableStateFlow<Double>(dataR.servings)//几倍

    private val baseViewModel: GlobalViewModel by lazy {
        GlobalViewModel.getInstance(application)
    }

    override fun useDefaultImmersive() {
        ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
//            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            binding.clTop.setPadding(0, systemBars.top, 0, systemBars.bottom)
            binding.llb.setPadding(0, 0, 0, systemBars.bottom)
            insets
        }
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
    }

    private fun intentDataUI(intent: Intent) {
        dataR = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            intent.getSerializableExtra("recentlyEatenData", RecentlyEatenData::class.java) ?: RecentlyEatenData()
        } else {
            @Suppress("DEPRECATION")
            (intent.getSerializableExtra("recentlyEatenData") as RecentlyEatenData?) ?: RecentlyEatenData()
        }
        mulValue.update { dataR.servings }

        kotlin.runCatching {
            if (dataR.type == 2 || dataR.type == 4) {
                dataR.ingredients?.let {
                    mIngredientsList = Gson().fromJson(it, Array<ScanIngredientBean>::class.java).toList()
                }
            }
        }

        Log.e(TAG, "ingredientsList=${mIngredientsList.size}")
        if (mIngredientsList.isEmpty()){
            binding.llIngredients.visibility=View.GONE
        }

        binding.rv.adapter = adapter
        adapter.submit(mIngredientsList)
        adapter.removeAction = {
            val cakSum = mIngredientsList.filter { !it.removed }.sumOf { it.caloriesKcal }
            dataR.caloriesDaily = (cakSum * mulValue.value).toInt()
            binding.tvCalories.text = dataR.caloriesDaily.toString()
        }
        adapter.submit(mIngredientsList)

        if (dataR.createTime.isNotEmpty()) {
            val instant = Instant.ofEpochMilli(dataR.createTime.toLong())
            val localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault())
            val formatter = DateTimeFormatter.ofPattern("hh:mm a")
            val formattedTime = localDateTime.format(formatter)
            binding.tvTime.text = formattedTime
        }

        binding.tvName.text = dataR.foodName

        binding.tvCalories.text = (dataR.caloriesDaily * mulValue.value).toInt().toString()
        binding.tvProtein.text = (dataR.proteinDaily * mulValue.value).toInt().toString()
        binding.tvCarbs.text = (dataR.carbsDaily * mulValue.value).toInt().toString()
        binding.tvFats.text = (dataR.fatsDaily * mulValue.value).toInt().toString()

        binding.pbScore.progress = dataR.healthScore?.toInt() ?: 0
        binding.tvScore.text = "${dataR.healthScore?.toInt()}/10"


        Glide.with(this).load(dataR.img)
            .override(
                com.bumptech.glide.request.target.Target.SIZE_ORIGINAL,
                resources.getDimensionPixelSize(R.dimen.dp_350)
            ) // maxHeight 为最大高度
            .into(binding.iv)
        //查询收藏
        lifecycleScope.launch {
            val aa = CloudStore.getListItem<CollectFoodInfoData>(
                CloudStore.DOC_SAVE_FOOD_COLLECT_DATA,
                CloudStore.DOC_SAVE_FOOD_COLLECT_DATA,
                dataR.createTime
            )
            if (aa != null) {
                binding.ivBookmark.isSelected = true
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        intentDataUI(intent)

        onBackPressedDispatcher.addCallback {
            finishAfterTransition()
        }
        binding.flBack.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }

        binding.llCal.setThrottleListener {
            lifecycleScope.launch {
                val result = goToAcForResult(EditPlanGoalAc::class.java) {
                    putExtra("type", TYPE_CALORIES)
                    putExtra("value", dataR.caloriesDaily * mulValue.value)
                }
                val value = result.data?.getDoubleExtra("result", 0.0) ?: return@launch
                dataR.caloriesDaily = (value / mulValue.value).toInt()
                binding.tvCalories.text = (dataR.caloriesDaily * mulValue.value).toString()
            }
        }
        binding.clProtein.setThrottleListener {
            lifecycleScope.launch {
                val result = goToAcForResult(EditPlanGoalAc::class.java) {
                    putExtra("type", TYPE_PROTEIN)
                    putExtra("value", dataR.proteinDaily * mulValue.value)
                }
                val value = result.data?.getDoubleExtra("result", 0.0) ?: return@launch
                dataR.proteinDaily = (value / mulValue.value).toInt()
                binding.tvProtein.text = (dataR.proteinDaily * mulValue.value).toString()
            }

        }
        binding.clCarbs.setThrottleListener {
            lifecycleScope.launch {
                val result = goToAcForResult(EditPlanGoalAc::class.java) {
                    putExtra("type", TYPE_CARBS)
                    putExtra("value", dataR.carbsDaily * mulValue.value)
                }
                val value = result.data?.getDoubleExtra("result", 0.0) ?: return@launch
                dataR.carbsDaily = (value / mulValue.value).toInt()
                binding.tvCarbs.text = (dataR.carbsDaily * mulValue.value).toString()
            }

        }
        binding.clFats.setThrottleListener {
            lifecycleScope.launch {
                val result = goToAcForResult(EditPlanGoalAc::class.java) {
                    putExtra("type", TYPE_FATS)
                    putExtra("value", dataR.fatsDaily * mulValue.value)
                }
                val value = result.data?.getDoubleExtra("result", 0.0) ?: return@launch
                dataR.fatsDaily = (value / mulValue.value).toInt()
                binding.tvFats.text = (dataR.fatsDaily * mulValue.value).toString()
            }
        }

        lifecycleScope.launch {
            mulValue.collectLatest {
                dataR.servings = it
                binding.tvValue.text = formatDouble(it)
                binding.tvCalories.text = (dataR.caloriesDaily * it).toInt().toString()
                binding.tvProtein.text = (dataR.proteinDaily * it).toInt().toString()
                binding.tvCarbs.text = (dataR.carbsDaily * it).toInt().toString()
                binding.tvFats.text = (dataR.fatsDaily * it).toInt().toString()
                adapter.notifyMulValue(it)
            }
        }

        binding.ivReduce.setOnClickListener {
            if (mulValue.value <= 0.5) return@setOnClickListener
            mulValue.update { it - 0.5 }
        }
        binding.ivAdd.setOnClickListener {
            if (mulValue.value >= 99) return@setOnClickListener
            mulValue.update { it + 0.5 }
        }

        binding.tvDone.setOnClickListener {
            setResult(Activity.RESULT_OK, Intent().apply {
                putExtra("recentlyEatenData", dataR)
            })
            finish()
        }
        binding.llAI.setThrottleListener {
            lifecycleScope.launch {
                val result = goToAcForResult(FixResultAc::class.java) {
                    putExtra("recentlyEatenData", dataR)
                    putExtra("type", "foodDetail")
                }
                result.data?.let {
                    intentDataUI(it)
                }
            }
        }
        binding.ivBookmark.setOnClickListener {
            val f = !binding.ivBookmark.isSelected
            //收藏
            if (f) {
                CloudStore.addToList(
                    DOC_SAVE_FOOD_COLLECT_DATA,
                    date = DOC_SAVE_FOOD_COLLECT_DATA,
                    key = dataR.createTime,
                    data = dataR.toCollectFoodInfoData().apply {
                        type = 2
                    }
                )
                binding.ivBookmark.isSelected = true
            } else {
                CloudStore.deleteList(
                    DOC_SAVE_FOOD_COLLECT_DATA,
                    date = DOC_SAVE_FOOD_COLLECT_DATA,
                    key = dataR.createTime
                )
                binding.ivBookmark.isSelected = false
            }
        }

        binding.ivMore.setOnClickListener {
            binding.deleteText.visibility = View.VISIBLE
            lifecycleScope.launch {
                delay(5000)
                binding.deleteText.visibility = View.INVISIBLE
            }
        }
        binding.deleteText.setOnClickListener {
            deleteList(
                CloudStore.DOC_RECENTLY_LIST_DATA,
                DateEx.getDayOfMonth(),
                dataR.createTime
            )
            baseViewModel.deleteRecentlyData(dataR)
            finish()
        }
    }

    fun formatDouble(value: Double): String {
        return if (value == value.toInt().toDouble()) {
            value.toInt().toString()
        } else {
            value.toString()
        }
    }


}